package com.jinyang.jetpackdemo.service

import android.app.AlertDialog
import android.app.Dialog
import android.app.Service
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import com.jinyang.jetpackdemo.util.LjyLogUtil
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MyService : Service() {

    private lateinit var job: Job
    private var myBinder: MyBinder? = null

    override fun onCreate() {
        super.onCreate()
        LjyLogUtil.d("MyService.onCreate:${Thread.currentThread().name}")
        myBinder = MyBinder()
//        job = GlobalScope.launch {
//            repeat(20) {
//                LjyLogUtil.d("${Thread.currentThread().name}_job:$it")
//                delay(1000)
//            }
//            stopSelf()
//        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LjyLogUtil.d("MyService.onStartCommand: intent=$intent _ flags=$flags _ startId=$startId")
        val num1 = intent?.getIntExtra("key1", -1)
        LjyLogUtil.d("num1:$num1")
        for (i in 1..4) {
            LjyLogUtil.d("doSomething:$i")
        }
        Thread {
            for (i in 1..100) {
                LjyLogUtil.d("${Thread.currentThread().name}_doSomethingThread:$i")
                Thread.sleep(1000)
            }
        }.start()
        val builder: AlertDialog.Builder = AlertDialog.Builder(applicationContext)
        builder.setMessage("Hello,My name is Message.")
        builder.setNegativeButton("CANCEL", null)
        builder.setPositiveButton("OK") { dialog, which ->
            dialog.dismiss()
        }
        val dialog: Dialog = builder.create()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0
            if (!Settings.canDrawOverlays(this)) {
                //启动Activity让用户授权
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                // Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.data = Uri.parse("package:$packageName");
                startActivity(intent)
                return super.onStartCommand(intent, flags, startId)
            }
            dialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
        } else {
            dialog.window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        }
        dialog.show()

        return super.onStartCommand(intent, flags, startId)
//        return START_NOT_STICKY
        //START_CONTINUATION_MASK  :
        //START_STICKY: 如果service进程被kill掉，保留service的状态为开始状态，但不保留递送的intent对象。
        // 随后系统会尝试重新创建service，由 于服务状态为开始状态，所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。
        // 如果在此期间没有任何启动命令被传 递到service，那么参数Intent将为null。
        //START_NOT_STICKY:“非粘性的”。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统不会自动重启该服务
        //START_REDELIVER_INTENT：重传Intent。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统会自动重启该服务，并将Intent的值传入。
        //START_STICKY_COMPATIBILITY：START_STICKY的兼容版本，但不保证服务被kill后一定能重启。
    }


    override fun onBind(intent: Intent): IBinder? {
        LjyLogUtil.d("MyService.onBind: $intent")
        val num2 = intent.getIntExtra("key2", -1)
        LjyLogUtil.d("num2:$num2")
        myBinder?.num = num2
        return myBinder
    }

    override fun onUnbind(intent: Intent?): Boolean {
        LjyLogUtil.d("MyService.onUnbind: $intent")
        return super.onUnbind(intent)
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
        LjyLogUtil.d("MyService.onRebind: $intent")
    }

    override fun onDestroy() {
        super.onDestroy()
        LjyLogUtil.d("MyService.onDestroy")
    }

    class MyBinder : Binder() {
        var num: Int? = 0
        fun doSomeWork() {
            LjyLogUtil.d("MyService.MyBinder.doSomeWork, num=$num")
        }
    }
}